<?php

namespace App\Http\Controllers\Admin;

use App\Model\Admin;
use Firebase\JWT\JWT;
use App\Http\Controller;
use App\Repository\AdminRepository;

class TokenController extends Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->admin = new AdminRepository();
    }

    public function token($request, $response, $args)
    {
        $params = $request->getParams();

        if(false == isset($params['username'])) {
            return $response->withJson(['code' => '422', 'message' => '请输入用户名']);
        }

        if(false == isset($params['password'])) {
            return $response->withJson(['code' => '422', 'message' => '请输入密码']);
        }

        $admin = $this->admin->show();

        if(is_null($admin)) {
            return $response->withJson(['code' => '422', 'message' => '用户名或密码错误']);
        }

        if(false == password_verify($params['password'], $admin->password)) {
            return $response->withJson(['code' => '422', 'message' => '用户名或密码错误']);
        }

        $iat = time();
        $exp = time() + 10800;

        $header = [
            'typ' => 'JWT',
            'alg' => 'HS256'
        ];

        $payload = [
            'iat' => $iat,
            'exp' =>  $exp,
            'sub' => ['created_at' => $admin->created_at],
            'jti' => base64_encode(random_bytes(32)),
        ];

        $token =[
            'status' => '200',
            'token' => JWT::encode($payload, getenv('JWT_ADMIN_SECRET'))
        ];

        return $response->withJson($token);
    }

}
